package com.webservice.impl.allot;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.webservice.dao.IAllotOutBillBackDao;
import com.webservice.dao.Pub;
import com.webservice.dao.PubBaseDao;
import com.webservice.service.IBaseService;
import com.webservice.utils.DateTimeTool;
import com.webservice.utils.MyApplicationContextUtil;
import com.webservice.utils.UUIDUtil;
import com.webservice.utils.VOXMLMapping;
import com.webservice.vo.AllotOutBillDetailInfo;
import com.webservice.vo.AllotOutBillFromXml;
import com.webservice.vo.AllotOutBillImeiInfo;
import com.webservice.vo.Product;
import com.webservice.vo.Seri;

/**
 * 
 * @author Andy billtype:
 * 
 */
@Service("B1002")
public class AllotOutBillBackService implements IBaseService {
	private static Logger logger = Logger.getLogger(AllotOutBillBackService.class);

	@Autowired
	@Qualifier("AllotOutBillBackDao")
	private IAllotOutBillBackDao allotOutBillBackDao;

	@Override
	public String returnData(String xml, PubBaseDao baseDao, String ip) throws Exception {
		String allotcode="";
		String outcode="";
		String returnxml="";
		String intoUUID = UUIDUtil.getUUID();
		String outUUID = UUIDUtil.getUUID();
		// 成对标志
		String pairflag = DateTimeTool.getDateTimeString(new Date(),"yyyymmddHHmmss:sss").replace(":", "");
		try{
			return dealBusiness(xml,baseDao,ip);
		} catch (Exception e) {
			e.printStackTrace();
			try{
				returnxml=returnXml(allotcode,outcode,"-1","报文解析失败");
				Pub.insertLog(baseDao, intoUUID, ip, "14", "", xml, "into",pairflag,"0");//调拨出库
				Pub.insertLog(baseDao, outUUID, ip, "14", outcode, returnxml, "out",pairflag,"1");//调拨出库
				Pub.insertDealResultLog(baseDao, outUUID, "WMS", "B2B", "处理异常", e.getMessage());
			}catch(Exception et){
				et.printStackTrace();
				throw new Exception(returnxml);
			}
			throw new Exception(returnxml);
		} 
	}
	
	@Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
	private String dealBusiness(String xml, PubBaseDao baseDao, String ip) throws Exception{
		String allotcode="";
		String outcode="";
		String returnxml="";
		String intoUUID = UUIDUtil.getUUID();
		String outUUID = UUIDUtil.getUUID();
		// 成对标志
		String pairflag = DateTimeTool.getDateTimeString(new Date(),"yyyymmddHHmmss:sss").replace(":", "");
		try {
			AllotOutBillFromXml allotOutBill = (AllotOutBillFromXml) VOXMLMapping
					.fromXML(xml, AllotOutBillFromXml.class, null);// 反射xml-->实体类
			Pub.insertLog(baseDao, intoUUID, ip, "14", allotOutBill.getOutcode(), xml, "into",pairflag,"0");//调拨出库
			String validateResult=this.validateXml(allotOutBill);
			if (!"".equals(validateResult)) {
				allotcode=allotOutBill.getAllotcode();
				outcode=allotOutBill.getOutcode();
				returnxml=returnXml(allotcode,outcode,"-1",validateResult);
				Pub.insertLog(baseDao, outUUID, ip, "14", outcode, returnxml, "out",pairflag,"1");//调调拨出库
				Pub.insertDealResultLog(baseDao, outUUID, "WMS", "B2B", "处理异常", validateResult);
				return returnxml;
			} else {
				allotcode=allotOutBill.getAllotcode();
				outcode=allotOutBill.getOutcode();
				String state=this.allotOutBillBackDao.getOutStoreState(outcode);
				if("3".equals(state)){
					returnxml=returnXml(allotcode,outcode,"-1","该出库单已出库，不能重复出库");
					Pub.insertLog(baseDao, outUUID, ip, "14", outcode, returnxml, "out", pairflag,"1");//调拨出库
					Pub.insertDealResultLog(baseDao, outUUID, "WMS", "B2B", "处理异常", "该出库单已出库，不能重复出库");
				}
				List<Product> plist = allotOutBill.getProducts();
				List<AllotOutBillDetailInfo> details = new ArrayList<AllotOutBillDetailInfo>();
				List<AllotOutBillImeiInfo> imeiInfos = new ArrayList<AllotOutBillImeiInfo>();
				for (Product p : plist) {
					int quantity = allotOutBillBackDao.getQuantity(
							allotOutBill.getAllotcode(), p.getProductcode()+"",
							p.getSupplyid() + "");
					// if(!StringUtils.equals(quantity+"", p.getQuantity())){
					// validateResult=validateResult+"";
					// }
					AllotOutBillDetailInfo detail = new AllotOutBillDetailInfo();
					detail.setActualnum(quantity);// 实际出库数量
					detail.setBillcode(allotOutBill.getOutcode());// 出库单号
					detail.setDr(0);
					String pk=this.allotOutBillBackDao.getOutBillDetailPk(allotOutBill.getOutcode(), p.getProductcode()+"",
							p.getSupplyid() + "");
					if("".equals(pk)){
						//pk = UUIDUtil.getUUID();
						returnxml=returnXml(allotcode,outcode,"-1","出库单明细缺失！");
						Pub.insertLog(baseDao, outUUID, ip, "14", outcode, returnxml, "out", pairflag,"1");//调拨出库
						Pub.insertDealResultLog(baseDao, outUUID, "WMS", "B2B", "处理异常", "出库单明细缺失");
						return returnxml;
					}
					detail.setPk_outbilletail(pk);// 出库明细主键
					detail.setProducid(p.getProductcode());// 产品号
					detail.setQuantity(p.getQuantity());// 应出库数
					detail.setSupplyid(p.getSupplyid());// 供应商id
					detail.setTs(DateTimeTool.getDateTimeString(new Date()));// 出库时间
					details.add(detail);
					List<Seri> slist = p.getSerials();
					if(slist != null && slist.size() > 0){
						for (Seri s : slist) {// 获得产品的imei号
							AllotOutBillImeiInfo imei = new AllotOutBillImeiInfo();
							imei.setDr(0);
							imei.setImei(s.getImei());
							imei.setPk_outbilletail(pk);
							imei.setPk_outimei(UUIDUtil.getUUID());
							imei.setTs(DateTimeTool.getDateTimeString(new Date()));
							imeiInfos.add(imei);
						}
					}
				}
				// 1,更新出库单状态为已出库
				this.allotOutBillBackDao.updateOutBill(allotOutBill
						.getOutcode());
				this.allotOutBillBackDao.updateAllotState(allotcode);//更新调拨单状态为在途
				// 2,往出库明细表更新出库明细
				this.allotOutBillBackDao.batchInsertOutBillDetail(details);
				// 3，往出库串号表插入串号信息
				this.allotOutBillBackDao.batchInsertOutBillImei(imeiInfos);
			}
			returnxml=returnXml(allotcode,outcode,"0","成功");
			Pub.insertLog(baseDao, outUUID, ip, "14", outcode, returnxml, "out",pairflag,"1");//调拨出库
			Pub.insertDealResultLog(baseDao, outUUID, "WMS", "B2B", "成功", "调拨出库回传处理成功");
			return returnxml;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} 
	}

	private String returnXml(String allotcode,String outcode,String flag,String text){
		String returnXml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><returnmsg><allotcode>"+allotcode+"</allotcode><outcode>"+outcode+"</outcode>" +
				"<result>"+flag+"</result><msg>"+text+"</msg></returnmsg>";
		return returnXml;
	}

	private String validateXml(AllotOutBillFromXml allotOutBill) throws Exception {
		String validateResult = "";
		if(StringUtils.isBlank(allotOutBill.getAllotcode())){
			validateResult="调拨单号不能为空";
			return validateResult;
		}
		if(StringUtils.isBlank(allotOutBill.getOutcode())){
			validateResult="出库单号不能为空";
			return validateResult;
		}
		List<Product> products=allotOutBill.getProducts();
		if(products==null||products.size()<0){
			validateResult="product不能为空！";
			return validateResult;
		}else{
			for(Product product:products){
				if(StringUtils.isBlank(product.getProductcode()+"")){
					validateResult="产品编码不能为空";
					return validateResult;
				}
				if(StringUtils.isBlank(product.getQuantity()+"")){
					validateResult="产品数量不能为空";
					return validateResult;
				}
				if(product.getSupplyid()<0){
					validateResult="供应商不能为空";
					return validateResult;
				}
				List<Seri> seris= product.getSerials();
				if(seris==null||seris.size()!=product.getQuantity()){
//					validateResult="quantity数量和imei个数不相等";
//					return validateResult;
				}else{
					for(Seri seri:seris){
						if(StringUtils.isBlank(seri.getImei())){
							validateResult="Imei不能为空";
							return validateResult;
						}
					}
				}
			}
		}
		return validateResult;
	}

	public static void main(String[] args) {
		String xml = 
//				"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <allotoutback>  <allotcode>1</allotcode><outcode>Yoyoout01</outcode>  <products>    <product>      <productcode>222</productcode>      <quantity>100</quantity>      <supplyid>11</supplyid>    </product>    <product>      <productcode>12</productcode>      <quantity>50</quantity>      <supplyid>11</supplyid>      <serials>        <seri>          <imei>356131100000003</imei>        </seri>        <seri>          <imei>356131100000004</imei>        </seri>        <seri>          <imei>356131100000005</imei>        </seri>        <seri>          <imei>356131100000006</imei>        </seri>        <seri>          <imei>356131100000007</imei>        </seri>        <seri>          <imei>356131100000008</imei>        </seri>        <seri>          <imei>356131100000009</imei>        </seri>        <seri>          <imei>356131100000010</imei>        </seri>        <seri>          <imei>356131100000011</imei>        </seri>        <seri>          <imei>356131100000012</imei>        </seri>        <seri>          <imei>356131100000013</imei>        </seri>        <seri>          <imei>356131100000015</imei>        </seri>        <seri>          <imei>356131100000016</imei>        </seri>        <seri>          <imei>356131100000017</imei>        </seri>        <seri>          <imei>356131100000018</imei>        </seri>        <seri>          <imei>356131100000019</imei>        </seri>        <seri>          <imei>356131100000021</imei>        </seri>        <seri>          <imei>356131100000022</imei>        </seri>        <seri>          <imei>356131100000023</imei>        </seri>        <seri>          <imei>356131100000024</imei>        </seri>        <seri>          <imei>356131100000025</imei>        </seri>        <seri>          <imei>356131100000026</imei>        </seri>        <seri>          <imei>356131100000027</imei>        </seri>        <seri>          <imei>356131100000028</imei>        </seri>        <seri>          <imei>356131100000030</imei>        </seri>        <seri>          <imei>356131100000031</imei>        </seri>        <seri>          <imei>356131100000032</imei>        </seri>        <seri>          <imei>356131100000033</imei>        </seri>        <seri>          <imei>356131100000035</imei>        </seri>        <seri>          <imei>356131100000036</imei>        </seri>        <seri>          <imei>356131100000037</imei>        </seri>        <seri>          <imei>356131100000038</imei>        </seri>        <seri>          <imei>356131100000039</imei>        </seri>        <seri>          <imei>356131100000040</imei>        </seri>        <seri>          <imei>356131100000041</imei>        </seri>        <seri>          <imei>356131100000042</imei>        </seri>        <seri>          <imei>356131100000043</imei>        </seri>        <seri>          <imei>356131100000044</imei>        </seri>        <seri>          <imei>356131100000045</imei>        </seri>        <seri>          <imei>356131100000046</imei>        </seri>        <seri>          <imei>356131100000047</imei>        </seri>        <seri>          <imei>356131100000049</imei>        </seri>        <seri>          <imei>356131100000050</imei>        </seri>        <seri>          <imei>356131100000051</imei>        </seri>        <seri>          <imei>356131100000052</imei>        </seri>        <seri>          <imei>356131100000029</imei>        </seri>        <seri>          <imei>356131100000034</imei>        </seri>        <seri>          <imei>356131100000020</imei>        </seri>        <seri>          <imei>356131100000014</imei>        </seri>        <seri>          <imei>356131100000048</imei>        </seri>      </serials>    </product>  </products></allotoutback>"
//				+ "<products><product><supplyid>1</supplyid><productcode>item1</productcode><quantity>2</quantity><serials><seri><imei>1"
//				+ "</imei></seri><seri><imei>2</imei> </seri> </serials>  <A></A></product></products></allotoutback>";
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <allotoutback><allotcode>12</allotcode>  <outcode>Yoyoout01</outcode>  <products>    <product>      <productcode>1</productcode>      <quantity>100</quantity>      <supplyid>2</supplyid> <b></b>  <serials><seri>1</seri></serials><serials><seri>1</seri></serials>  </product>   </products></allotoutback>";
		AllotOutBillBackService a = new AllotOutBillBackService();
		try {
			// a.assembleData(xml);
//			System.out.println(a.validateXml(xml));
			AllotOutBillFromXml allotOutBill = (AllotOutBillFromXml) VOXMLMapping
			.fromXML(xml, AllotOutBillFromXml.class, null);// 反射xml-->实体类
			System.out.println(a.validateXml(allotOutBill));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("解析失败");
		}
	}

//	public IAllotOutBillBackDao allotOutBillBackDao {
//		IAllotOutBillBackDao allotOutBillBackDao=(IAllotOutBillBackDao) MyApplicationContextUtil.getContext().getBean("AllotOutBillBackDao");
//		return allotOutBillBackDao;
//	}
//
//	public void setAllotOutBillBackDao(IAllotOutBillBackDao allotOutBillBackDao) {
//		this.allotOutBillBackDao = allotOutBillBackDao;
//	}

	public DataSourceTransactionManager getTx() {
		
		DataSourceTransactionManager tx=(DataSourceTransactionManager) MyApplicationContextUtil.getContext().getBean("txManager");
		return tx;
	}

}
